/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.spring66.tutorial.dao.hibernate;


import com.spring66.tutorial.dao.UserDao;
import com.spring66.tutorial.model.User;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 *
 * @author TwinP
 */
public class HibernateUserDao extends HibernateDaoSupport implements UserDao {

    protected final Log log = LogFactory.getLog(getClass());

    @Override
    public User getUserByUsername(String username) {
        List result = getHibernateTemplate().find("from User user where user.username=?", username);
        User user = (User) result.get(0);
        log.debug("user's username: " + user.getUsername());
        return user;
    }

    @Override
    public User saveUser(User user) {
        getHibernateTemplate().saveOrUpdate(user);
        log.debug("user's id: " + user.getUserId());
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getHibernateTemplate().flush();
        return user;
    }

    @Override
    public User getUser(Long userId) {
        return (User)getHibernateTemplate().get(User.class, userId);
    }

    @Override
    public void removeUser(Long userId) {
        getHibernateTemplate().delete(this.getUser(userId));
    }

    @Override
    public List<User> getAllUser(){
        return getHibernateTemplate().find("from User user");
    }

    @Override
    public void removeUsers(List users){
        getHibernateTemplate().deleteAll(users);
    }
}
